import LiabilityAPI from '@/api/Liability';
import {
  Box,
  Icon,
  mapField,
  PaginationTable,
  PopoverConfirm,
  SearchFields,
  useCall,
  usePaginationCommon,
} from '@/components';
import { LIABILITY_TYPE } from '@/constants/options';
import { forkHandler } from '@/utils';
import { Button, Space } from 'antd';
import React from 'react';
import LiabilityEditModal from './components/LiabilityEditModal';

const SEARCH_FIELDS = [
  [['searchFuzzy', 'liability_code'], '责任代码'],
  [['searchFuzzy', 'liability_name'], '责任名称'],
  [
    ['sectionStartParams', 'create_date'],
    '创建日期',
    'named-range',
    { endName: ['../', 'sectionEndParams', 'create_date'] },
  ],
].map(mapField);

const COLUMNS = [
  { title: '责任代码', dataIndex: 'liabilityCode', sorter: true },
  { title: '责任名称', dataIndex: 'liabilityName' },
  { title: '责任属性', dataIndex: 'liabilityType', map: LIABILITY_TYPE },
  {
    title: '创建日期',
    dataIndex: 'createDate',
    format: 'date',
    sorter: true,
    defaultSortOrder: 'descend',
  },
];

const ACTIONS = {
  edit: {
    dialog: LiabilityEditModal,
    itemProp: 'item',
    title: '编辑责任',
    text: <Button type='link' size='small' icon={<Icon type='edit' />} />,
  },
  del: {
    confirm: '确认删除此责任类型吗?',
    text: <Button type='link' size='small' icon={<Icon type='delete' />} />,
  },
};

function ResponsibilityPage() {
  const { tableRef, searchData, onSearch, onSelect, selectedRef, reset } = usePaginationCommon();

  const onAdd = useCall(forkHandler(LiabilityAPI.updateInsert, reset, true));
  const onBatchDel = useCall(forkHandler(() => LiabilityAPI.remove(selectedRef.current), reset, true));
  const onDel = useCall(forkHandler((row) => LiabilityAPI.remove([row.id]), reset, true));
  const onEdit = useCall(
    forkHandler(
      (r, i, data) =>
        LiabilityAPI.updateInsert({
          ...data,
          id: r.id,
        }),
      reset,
      true,
    ),
  );

  return (
    <>
      <SearchFields fields={SEARCH_FIELDS} onSubmit={onSearch} onReset={onSearch} />

      <Box flex jus='between' py={2}>
        <Space size='middle'>
          <PopoverConfirm content='确认删除已选择的责任吗?' onOk={onBatchDel}>
            <Button> 批量删除 </Button>
          </PopoverConfirm>
        </Space>
        <Space size='middle'>
          <LiabilityEditModal title='新增责任' onOk={onAdd}>
            <Button> + 新增 </Button>
          </LiabilityEditModal>
        </Space>
      </Box>

      <PaginationTable
        ref={tableRef}
        service={LiabilityAPI.findByPage}
        serviceData={searchData}
        columns={COLUMNS}
        actions={ACTIONS}
        actionWidth={100}
        rowSelection={{ onChange: onSelect }}
        onDel={onDel}
        onEdit={onEdit}
      />
    </>
  );
}

export default ResponsibilityPage;
